<template>
  <el-dialog
    v-el-drag-dialog
    title="订单转派"
    :visible.sync="visible"
    width="800px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="85px">
      <el-form-item label="申请人" prop="ownerName" class="block">
        <el-input v-model="temp.ownerName" disabled />
      </el-form-item>
      <el-form-item label="客户编号" prop="csmCode">
        <el-input v-model="temp.csmCode" disabled />
      </el-form-item>
      <el-form-item label="客户姓名" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="客户地址" prop="csmAddress" class="block">
        <el-input v-model="temp.csmAddress" disabled />
      </el-form-item>
      <el-form-item label="绑定司机" prop="bindDriverName">
        <el-input v-model="temp.bindDriverName" disabled />
      </el-form-item>
      <el-form-item label="值班人" prop="dutyName">
        <el-input v-model="temp.dutyName" disabled />
      </el-form-item>
      <el-form-item label="责任机构" prop="orgId">
        <el-tree-select
          v-model="temp.orgId"
          :clearable="false"
          :disabled="corpSettingData.sp6 >> 15 & 0x01"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: false,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人" prop="nextOwnerId">
        <el-select v-model="temp.nextOwnerId" filterable clearable :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择" @change="chooseOwner">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        确定
      </el-button>
    </div>
    <confirmClasses ref="confirmClasses" :parent-fun="reset" />
  </el-dialog>
</template>

<script>
  import { queryRefundOrderTransfer, queryOwnerList, csDeliverUserList, orderDutyCheck, queryDuty } from '@/api'
  import { mapGetters } from 'vuex'
  import confirmClasses from '@/views/components/ConfirmClasses'
  export default {
    name: 'transfer-order',
    components: {
      confirmClasses
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        ownersList: [],
        ownerId: '',
        orderCode: '',
        temp: {
          orgId: '',
          nextOwnerId: '',
          remark: ''
        },
        rules: {
          orgId: [{ required: true, message: '请选择组织机构', trigger: 'change' }],
          nextOwnerId: [{ required: true, message: '请选择处理人', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    methods: {
      async open(temp) {
        await Promise.all([
          // this.getOwnersList(temp.originOrgId),
          this.getOwnersListNew(temp.orgId),
          this.queryDuty(temp)])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              csmName: `${temp.csmName}(${temp.contactPhone})`,
              remark: '',
              orgId: temp.orgId,
              nextOwnerId: temp.originOwnerId
            })
            if (temp.ownerType === 1) {
              this.temp.ownerName = `${temp.ownerName}(内部员工)`
            } else if (temp.ownerType === 2) {
              this.temp.ownerName = `${temp.ownerName}(客户)`
            }
          }
        })
      },
      // 获取上次上次配送人员
      async queryDuty(temp) {
        const res = await queryDuty({ csmId: temp.csmId })
        if (res.data) {
          this.temp.bindDriverName = res.data.driverName ? res.data.driverName : ''
          this.temp.dutyName = res.data.dutyName ? res.data.dutyName : ''
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        // this.getOwnersList(value.orgId)
        this.getOwnersListNew(value.orgId)
        this.$set(this.temp, 'nextOwnerId', '')
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 查询处理人列表（新）
      async getOwnersListNew(orgId) {
        const res = await csDeliverUserList({ deliveryOrgId: orgId, utype: 32 })
        this.ownersList = res.data.filter(item => item.userId !== this.ownerId)
      },
      async chooseOwner(val) {
        const info = this.ownersList.find(item => item.userId === val)
        if (val) {
          const res = await orderDutyCheck({ ownerId: val, corpSN: info.corpSN })
          if (res.data === 1) {
            this.$refs.confirmClasses.open(info)
          }
        }
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const user = this.ownersList.find(item => item.userId === this.temp.nextOwnerId)
          const org = this.orgList.find(item => item.orgId === this.temp.orgId)
          const params = {
            nextOwnerName: user.userName,
            nextOwnerId: user.userId,
            nextOwnerCode: user.userCode,
            orderCode: this.temp.orderCode,
            orgId: this.temp.orgId,
            orgSNNo: org.orgSNNo,
            orgName: org.orgName,
            remark: this.temp.remark
          }
          this.submit(params)
        })
      },
      async submit(params) {
        const res = await queryRefundOrderTransfer(params)
        this.resolve()
        if (res) {
          if (res.data === 2) {
            this.noTransfer()
          } else {
            this.visible = false
            this.$notify({
              title: '提示',
              message: '操作成功!',
              type: 'success',
              duration: 2000
            })
          }
        }
      },
      // 不允许转派
      noTransfer() {
        this.$confirm('支付方式为预付卡的订单，不允许跨站转派', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      reset() {
        this.ownerId = ''
        this.orderCode = ''
        this.temp = {
          orgId: '',
          nextOwnerId: '',
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
